package com.baizhi.aop;

import cn.hutool.core.util.ArrayUtil;
import com.baizhi.annotation.LogRecord;
import com.baizhi.entity.BzAdmin;
import com.baizhi.entity.BzLog;
import com.baizhi.enums.LogTypeEnum;
import com.baizhi.mapper.BzLogMapper;
import com.baizhi.util.IpUtil;
import org.apache.catalina.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author yu
 */
@Aspect
@Component
public class LogAOP {
    @Autowired
    private BzLogMapper bzLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Around("@annotation(com.baizhi.annotation.LogRecord)")
    public Object logRecord(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long timeMillion=endTime-startTime;
        HttpSession session = request.getSession();
        BzAdmin bzAdmin = (BzAdmin) session.getAttribute("user");
        String username=null;
        if(bzAdmin==null){
            username="未登录";
        }else {
            username=bzAdmin.getUsername();
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String requestMethod = methodSignature.getMethod().toString();
        LogRecord annotation = methodSignature.getMethod().getAnnotation(LogRecord.class);
        LogTypeEnum operation = annotation.type();
        String description = annotation.content();
        Object[] args = joinPoint.getArgs();
        String requsetParam = ArrayUtil.toString(args);
        Date createDate = new Date();
        String ipAddress = IpUtil.getIpAddrByRequest(request);
        BzLog bzLog = new BzLog();
        bzLog.setUsername(username);
        bzLog.setCreateDate(createDate);
        bzLog.setDescription(description);
        bzLog.setIpAddress(ipAddress);
        bzLog.setOperation(operation.name());
        bzLog.setRequestMethod(requestMethod);
        bzLog.setRequestParam(requsetParam);
        bzLog.setTimeMillion(timeMillion);
        bzLogMapper.insert(bzLog);
        return proceed;
    }
}
